package com.Interface.interceptor;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.Interface.util.StaticValue;

public class SessionInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler, ModelAndView arg3) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		String reqUrl = request.getServletPath();
		if("/interface/userLogin".equals(reqUrl)) 
			return true;
		else if ("/interface/moaLogin".equals(reqUrl))
			return true;
		else if (reqUrl.matches(StaticValue.NO_INTERCEPTOR_PATH))//不拦截规则
			return true;
		int nosession =Integer.parseInt((request.getParameter("no_session")==null || request.getParameter("no_session").equals(""))?"0":request.getParameter("no_session"));
		if(nosession == 1)
			return true;
		HttpSession session=request.getSession();
		if(session.getAttribute(StaticValue.SESSION_USER_LOGIN_INFO) == null) {
			StringBuffer sb = new StringBuffer();
			HashMap<String, Object>  resultMap = new HashMap<String,Object>();
			HashMap<String, Object>  data = new HashMap<String,Object>();
			resultMap.put("code", 401);
			resultMap.put("msg", "权限不足未登陆");
			resultMap.put("data", data);
			response.setContentType("application/json;charset=utf-8");
			JSONObject json = new  JSONObject(resultMap);
			response.getWriter().write(json.toString());
			
			/*
			sb.append(resultMap);
			
			response.getWriter().write(sb.toString());
		    PrintWriter out = null;  
		    try {  
		        out = response.getWriter();  
		    } catch (IOException e) {  
		        e.printStackTrace();  
		    } finally {  
		        if (out != null) {  
		            out.close();  
		        }  
		    }*/
		    return false;
		}
		else
			return true;
		 
	}
}
